import {createRouter, createWebHistory} from 'vue-router';
import {getToken} from "@/utils/Storage.js";
import {isTokenExpired} from "@/utils/TokenUtils.js";

// 定义路由规则数组
const routes = [
    {
        path: '/login',
        name: 'Login',
        component: () => import("./views/LoginAndRegister.vue")
    },
    {
        path: '/',
        component: ()=>import("./layouts/Layout.vue"),
        // 如果有token，重定向到仪表盘或用户习惯的首页
        redirect: '/dashboard',
        children: [
            { path: 'dashboard', name: 'Dashboard', component: ()=>import("./views/Dashboard.vue") },
            { path: 'nutrition', name: 'Nutrition', component: ()=>import("./views/Nutrition.vue") }, // 建议为所有路由提供组件
            {
                path: 'workouts/:planId?', // path 包含一个可选的 :planId 参数
                name: 'Workouts',
                component: () => import("./views/Workouts.vue")
            },
            {
                path: 'template-editor/new', // 新建模板
                name: 'TemplateEditorNew',
                component: ()=>import("./views/TemplateEditor.vue")
            },
            {
                path: 'template-editor/:id', // 编辑模板，:id 是动态参数
                name: 'TemplateEditorEdit',
                component: ()=>import("./views/TemplateEditor.vue")
            },
            { path: 'freeWorkout', name: 'FreeWorkout', component: ()=>import("./views/ExerciseLibrary.vue") },
            { path: 'my-templates', name: 'MyTemplates', component: ()=>import("./views/MyTemplates.vue") }, // <-- 新增路由
            { path: 'chat', name: 'Chat', component: ()=>import("./views/Chat.vue") }, // 建议为所有路由提供组件
        ],
    },
];

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    routes
});

//路由守卫
router.beforeEach((to, from, next) => {
    const token = getToken();
    const tokenExpired = token && isTokenExpired(token);
    const whiteList = ['/login'];

    if (token && !tokenExpired) {
        if (to.path === '/login') {
            next('/dashboard'); // 登录后默认跳转到仪表盘
        } else {
            next();
        }
    } else {
        if (!whiteList.includes(to.path)) {
            next('/login');
        } else {
            next();
        }
    }
});

export default router;